<template>
  <!-- 页面-菜单管理-添加 -->
  <div class="sidelip-box ldap-content">
    <Row
      :gutter="16"
      class="table-border-top ldap-content-padding"
    >
      <Col span="18" class="table-border">
        <div>
          <!-- 搜索区域 -->
          <div class="search-bar">
            <span class="select-user">已选{{selectTable.length}}项</span>
            <Form :model="searchForm" slot="adaption-bar" inline>
              <FormItem>
                <Input
                    suffix="ios-search"
                    type="text"
                    v-model.trim="searchForm.userOrName"
                    :placeholder="$t('module.userManage.searchKeywords')"
                    clearable
                    @input="search"
                    @on-clear="search"
                  />
              </FormItem>
              <FormItem>
                <Input
                  suffix="ios-search"
                  type="text"
                  v-model.trim="searchForm.setId"
                  :placeholder="`${$t('module.userManage.search')}${$t('module.userManage.orgNum')}`"
                  clearable
                  @input="search"
                  @on-clear="search"
                />

              </FormItem>
              <FormItem>
                <Input
                  suffix="ios-search"
                  type="text"
                  v-model.trim="searchForm.deptId"
                  clearable
                  :placeholder="`${$t('module.userManage.search')}${$t('module.userManage.deptCode')}`"
                  @input="search"
                  @on-clear="search"
                />
              </FormItem>
            <Input type="text" class="form-control" style="display:none" />
          </Form>

          </div>
          <InnerPageTable ref="tableLdap" :config="tableConfig"></InnerPageTable>
        </div>
      </Col>
      <Col span="6" class="table-border">
        <div class="select-user-list">
          <div class="top-content">
            <span class="select-user-num">已选择用户：{{selectTable.length}}个</span>
            <span class="clear-span" @click="deleteUser" v-if="selectTable.length > 0">清空</span>
          </div>
          <div class="user-list">
            <div class="user-info" v-for="item in selectTable" :key="item.id">
              <span>{{item.userName}} ({{item.userId}})</span>
              <Icon class="close-icon" type="md-close" @click="deleteUser(item)"/>
            </div>
          </div>
        </div>
      </Col>
    </Row>
    <div class="app-info">
      <div class="app-title"> <span class="title">可访问应用授权</span> <span class="tip">为上方已选择用户进行授权</span></div>
      <AllotApp
      :tenantCodeAndUser="tenantCodeAndUser"
      :selectApp="currentAppVos"
      @handleAllotApp="getSelectAllotApp"
      ></AllotApp>
    </div>

  </div>
</template>

<script>
import locales from "./locales.js";
import { codeReg } from "@/const.js";
import { ldapColumns, selectLdapColumns } from "./colomns";
import selectOrganization from "./selectOrganization.vue";

import userManageAPI from "@/api/userManageApi";
import { batchAddTenantAdmin } from "@/api/teantManageAPI.js";
import { CoreModuleName } from "@/const";
import AllotApp from "./AllotApp";
const RIPPLES = "ripples";

// import { delete } from "vue/types/umd";

// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  name: "menu-edit",
  mixins: [locales],
  components: {AllotApp},
  props: {
    propsTenantCode: {
      type: String,
      default: () => ""
    },
    userInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    USER_DETAIL: {
      type: Boolean,
      default() {
        return false;
      }
    },
    ACCESSIBLE_APP: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  data() {
    return {
      currentUserInfo: $store.state[CoreModuleName].userInfo,
      tenantCodeAndUser: {
        tenantCode: "",
        category: 0
      },
      currentAppVos: [], // 选中的全部APP
      fun: null,
      showDrawer: false,
      delList: [],
      allSelect: [],
      selectUserNum: 0,
      showLadpUser: true,
      modelForm: {
        orgName: "",
        orgId: "",
        orgCode: "",
        orgPath: "",
        addAssignUserVos: [
          {
            applicationCode: "RIPPLES.crc",
            applicationName: "Ripples",
            applicationType: 0
          }
        ]
      },
      //   tableConfig: {},
      searchForm: {
        userOrName: "",
        tenantCode: "",
        setId: "",
        deptId: "",
        locked: 0
      },
      selectTable: [],
      selectTableColoums: selectLdapColumns.bind(this)(),
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },

  computed: {
    is_Digitalplatform() {
      // 当前登录用户
      let currentUserInfo = this.currentUserInfo;
      let curTenantCode = currentUserInfo.tenantCode && currentUserInfo.tenantCode.toLowerCase() === RIPPLES;
      // let curUserCategory = currentUserInfo.category; // 用户类型: 1. 平台管理员 2. 租户管理员 3. 普通用户

      // if (curTenantCode || curUserCategory === 1 || curUserCategory === 2) {
      if (curTenantCode) {
        return true;
      } else {
        return false;
      }
    },
    tableConfig() {
      let _this = this;
      return {
        onSelectionChange(_selected) {
          _this.selectTable = _this.$refs["tableLdap"].allSelection;
          // _this.selectTable = _selected;
        },
        allSelection: [],
        // refrushSelection: _this.selectTable,
        hasSelectionArea: false,
        loadDataFn: this.getLdapList,
        columnsFn: ldapColumns.bind(this),
        autoFirst: false,
        selectionAreaItem: { key: "userId", title: "userName" }
      };
    }
  },
  created() {
    this.tenantCodeAndUser.tenantCode = this.userInfo.tenantCode;
    this.tenantCodeAndUser.category = this.userInfo.category;
    this.$emit("SetTitle", this.$t("module.userManage.ldapcreateuser"));
    this.$emit("SetPageWidth", 1100);
    this.$emit("SetPageMinHeight", 500);
    this.$emit("SetPageActions", this.actions);
    this.initCategorySelect(this.is_Digitalplatform);
  },
  mounted() {
    if (this.propsTenantCode) {
      this.searchForm.tenantCode = this.propsTenantCode;
    } else {
      this.searchForm.tenantCode = $store.state[CoreModuleName].userInfo.tenantCode;
    }
    this.$refs["tableLdap"].load(this.searchForm, 1);
  },
  methods: {
    initCategorySelect(state) {
      // 获取当前登录用户类型
      let tenantCode = this.currentUserInfo.tenantCode;
      // 根据当前用户类型显示相应用 - 户类型数据
      if (state) {
        this.tenantCodeAndUser.category = 1;
        this.tenantCodeAndUser.tenantCode = tenantCode
      } else {
        this.tenantCodeAndUser.category = 3;
        this.tenantCodeAndUser.tenantCode = tenantCode
      }
    },
    // 获取分配应用组件数据
    getSelectAllotApp(data) {
      const newSelected = data.selection;
      const newSelectedCode = newSelected.map(item => item.applicationCode);
      const oldSelectedCode = this.currentAppVos.map(item => item.applicationCode);
      //新增项
      const newAdded = newSelected.filter(item => oldSelectedCode.indexOf(item.applicationCode) == -1);
      //删除项
      const deletedApp = this.currentAppVos.filter(item => newSelectedCode.indexOf(item.applicationCode) == -1);
      this.modelForm.addAssignUserVos = newAdded;
      this.modelForm.delAssignUserVos = deletedApp;
    },
    // 选择组所属组织
    selectOrganization() {
      new this.$pageModal(
        selectOrganization,
        {
          props: {}
        },
        data => {
          if (data) {
            // 清除关联员工
            this.clearOrganization();
            this.modelForm.orgName = data.orgName;
            this.modelForm.orgId = data.orgId;
            this.modelForm.orgCode = data.orgCode;
            this.modelForm.orgPath = data.orgPath;
          }
        }
      );
    },
    // 清除所属组织
    clearOrganization() {
      this.modelForm.employeeId = "";
      return;
    },
    deleteUser(row) {
      if (!row.userId) {
        this.selectTable = [];
        this.$refs["tableLdap"].allSelection = this.selectTable;
      } else {
        this.selectTable = this.selectTable.filter(item => {
          return item.userId != row.userId;
        });
        this.$refs["tableLdap"].allSelection = this.selectTable;
      }
      let currentPage = this.$refs["tableLdap"].currentPage
      this.$refs["tableLdap"].load(this.searchForm, currentPage);
    },
    debounce(fn, wait = 300) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    showSelectUser() {
      this.showDrawer = true;
    },
    searchLdapUser(page = 1) {
      if (!this.propsTenantCode) {
        this.searchForm.tenantCode = $store.state[CoreModuleName].userInfo.tenantCode;
      } else {
        this.searchForm.tenantCode = this.propsTenantCode;
      }
      this.$refs["tableLdap"].load(this.searchForm, page);
    },
    search(page = 1) {
      this.debounce(this.searchLdapUser, 300);
    },
    selectUser(selectList) {},
    _extendParams(item) {
      // ldap变量和数字化中台字段名映射关系 key-数字化中台字段名 value-ldap字段名
      let ldapAndCenterkeysMap = {
        'employeeId': 'employeeId',
        'employeeName': 'userName',
        'ldapBuId': 'setId',
        'ldapDeptId': 'deptId',
        'ldapDisplayName': 'displayName',
        'ldapEmail': 'email',
        'ldapEmpNo': 'employeeId',
        'ldapEndDate': 'endDate',
        'ldapMemo': 'orgName',
        'ldapMobile': 'mobile',
        'ldapName': 'userName',
        'ldapNationalIDLast4': 'nationalIdLast4',
        'ldapPassword': 'userPassword',
        'ldapSetId': 'setId',
        'ldapStartDate': 'startDate',
        'ldapUid': 'userId'
      }
      let data = {}
      Object.keys(ldapAndCenterkeysMap).forEach(key => {
        data[key] = item[ldapAndCenterkeysMap[key]]
      })
      return data
    },
    save() {
      if (!this.selectTable.length) {
        this.$message.error({
          content: this.$t("common.warning.selctAddElement"),
          duration: 3
        });
        return;
      }
      // if (!this.modelForm.orgCode && !this.propsTenantCode) {
      //   this.$message.error({
      //     content: this.$t("module.treeManage.selectOrg"),
      //     duration: 3
      //   });
      //   return;
      // }
      let data = [];
      let userIds = [];
      let category = 1;

      // 当前用户为平台管理员，导入的是平台管理员；
      // 当前用户为租户管理员，普通用户，导入的是普通用户
      if (!this.propsTenantCode) {
        if ($store.state[CoreModuleName].userInfo.category === 1) {
          category = 1;
        } else {
          category = 3;
        }
      } else {
        category = 2;
      }
      this.selectTable.forEach(item => {
        data.push(
          Object.assign(item, this._extendParams(item), this.modelForm, {
            category: category,
            type: 5,
            tenantCode: this.propsTenantCode ? this.propsTenantCode : $store.state[CoreModuleName].userInfo.tenantCode
          })
        );
        userIds.push(item.userId);
      });
      this.actions[0].loading = true;

      if (!this.propsTenantCode) {
        userManageAPI
          .addLdapUser(data)
          .then(res => {
            this.actions[0].loading = false;
            this.$message.success({
              content: this.$t("common.createSuccess"),
              duration: 3
            });
            let alreadyData = {
              tenantCode: this.propsTenantCode
                ? this.propsTenantCode
                : $store.state[CoreModuleName].userInfo.tenantCode,
              userIds
            };
            userManageAPI.alreadyAddUser(alreadyData);
            this.$emit("Close", true);
          })
          .catch(error => {
            this.actions[0].loading = false;
          });
      } else {
        batchAddTenantAdmin(data)
          .then(res => {
            this.actions[0].loading = false;
            this.$message.success({
              content: this.$t("common.createSuccess"),
              duration: 3
            });
            let alreadyData = {
              tenantCode: this.propsTenantCode
                ? this.propsTenantCode
                : $store.state[CoreModuleName].userInfo.tenantCode,
              userIds
            };
            userManageAPI.alreadyAddUser(alreadyData);
            this.$emit("Close", true);
          })
          .catch(error => {
            this.actions[0].loading = false;
          });
      }
    },
    getLdapList({ responseProcess, param }) {
      userManageAPI.getLdapUser(param).then(data => {
        responseProcess(data.data);
      });
    }
  }
};
</script>
<style lang="less" scoped>
.dept-select {
  width: 300px;
  /deep/.ivu-form-item-content {
    display: inline-block;
  }
}

</style>

<style lang="less" scoped>
.ldap-content {
  background: #F4F6FD;
  display: block;
  .table-border-top {
    background: #FFFFFF;
  }
  .search-bar{
    display: flex;
    align-items: center;
    .select-user { 
      font-size: 14px;
      color: #858B9C;
      letter-spacing: 0.4px;
      font-weight: 400;
    }
    .ivu-form {
      display: flex;
      flex: 1;
      justify-content: end;
    }
    .ivu-form-item {
      margin-bottom: 0;
    }

  }
  .select-user-list {
    background: #F5F7FA;
    padding: 16px;
    height: 100%;
    .top-content { 
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 16px;
    }
    .user-list {
      width: 100%;
      height: calc(100% - 50px);
      overflow-y: auto;
      .user-info {
        background: #FFFFFF;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 6px 12px;
        margin-bottom: 12px;
        .close-icon {
          cursor: pointer;
        }
      }
    }
    .select-user-num {
      font-size: 14px;
      color: #333333;
      font-weight: 500;
    }
    .clear-span {
      color: var(--primary-color);
      cursor: pointer;
      &:hover {
        color: var(--btn-primary-hover-bg)
      }
    }
  }
  .ivu-col {
    height: 100%;
  }
  .app-info {
    background: #fff;
    padding: 0 20px 20px;
  }
  .app-title {
    border-bottom: 1px solid #DCDEE0;
    padding: 24px 4px;
    .title {
      font-size: 16px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
    }
    .tip {
      font-size: 14px;
      color: #999999;
      font-weight: 400;
    }

  }
  .ivu-btn-warning {
    background: #fff !important;
    color: #ff6f4b !important;
  }
  .ldap-content-note-drawer {
    display: flex;
    flex-direction: column;
    background: #fff;
    border-radius: 20px 0 0 20px;
    padding: 5px 2px 5px 5px;
    // width: 30px;
    display: flex;
    align-items: center;

    @keyframes enable-animation {
      to {
        transform: scale(1.2);
        opacity: 0;
      }
    }
    .ldap-content-bc {
      position: absolute;
      z-index: 999;
      top: 9px;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background: #ff6f4b;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      .ldap-content-icon {
        text-align: center;
        font-size: 18px;
      }
    }
    .container {
      background: #ffbeae;
      animation: enable-animation 1s infinite;
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }

    .ldap-content-tip {
      display: none;
      text-align: center;
      padding: 12px;
      // height: 180px;
      writing-mode: tb-rl;
      .ldap-content-tipN {
        writing-mode: initial;
      }
    }
    .arrow-right {
      // border: 1px solid #ff6f4b;
      border-left: none;
    }
    .arrow-left {
      // border: 1px solid #ff6f4b;
      border-right: none;
    }
    .ldap-content-note .ldap-content-tip-arrow {
      border: 1px solid #ff6f4b !important;
      border-left: none;
    }
  }
  .ldap-content-note {
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
    border-radius: 20px 0 0 20px;
    padding: 16px 4px;
    // width: 30px;
    display: flex;
    align-items: center;

    @keyframes ldap-content-bc {
      to {
        transform: scale(1.2);
        opacity: 0;
      }
    }
    .ldap-content-bc {
      position: absolute;
      z-index: 999;
      top: 21px;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background: #ff6f4b;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      .ldap-content-icon {
        text-align: center;
        font-size: 18px;
      }
    }
    .container {
      background: #ffbeae;
      animation: ldap-content-bc 1s infinite;
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }

    .ldap-content-tip {
      text-align: center;
      display: inline-block;
      padding: 12px;
      // height: 180px;
      writing-mode: tb-rl;
      .ldap-content-tipN {
        writing-mode: initial;
      }
    }
    .arrow-right {
      // border: 1px solid #ff6f4b;
      border-left: none;
    }
    .arrow-left {
      // border: 1px solid #ff6f4b;
      border-right: none;
    }
    .ldap-content-note .ldap-content-tip-arrow {
      border: 1px solid #ff6f4b !important;
      border-left: none;
    }
  }
  @keyframes ldap-content {
    to {
      background: #ff6f4b;
      color: #fff;
    }
  }
  .ldap-content-note-drawer:hover {
    animation: ldap-content 0.5s 1;
    // background: #ff6f4b;
    animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    .ldap-content-bc {
      background: #fff;
      color: #ff6f4b;
      .ldap-content-icon {
        text-align: center;
      }
    }
  }
  .ldap-content-note:hover {
    animation: ldap-content 0.5s 1;
    // background: #ff6f4b;
    animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    .ldap-content-bc {
      background: #fff;
      color: #ff6f4b;
      .ldap-content-icon {
        text-align: center;
      }
    }
  }
  .ldap-content-padding {
    height: 581px;
    width: 100%;
    align-items: flex-start !important;
    background: #FFFFFF;
    padding: 20px;
  }
  .ivu-table-wrapper {
    max-height: 460px !important;
    .ivu-table-body {
      max-height: 400px !important;
    }
  }
  .drawer-table {
    .arrow {
      display: inline-block;
      position: absolute;
      background: #ff6f4b;
      writing-mode: tb-rl;
      height: 64px;
      padding: 3px;
      top: 40%;
      left: 0;
      color: #fff;
      cursor: pointer;
      text-align: center;
    }
    // .ivu-checkbox-checked .ivu-checkbox-inner {
    //   border: none !important;
    // }
    // .ivu-checkbox-checked .ivu-checkbox-inner:after {
    //   content: "X";
    //   display: table;
    //   width: 6px;
    //   height: 6px;
    //   position: absolute;
    //   top: 3px;
    //   left: 3px;
    //   border: 0;
    //   border-top: 0;
    //   border-left: 0;
    //   transform: rotate(0deg) scale(1);
    //   transition: all 0.2s ease-in-out;
    //   background-color: #fff;
    // }
  }
  .ivu-drawer-body {
    overflow: initial;
  }
}
.ivu-drawer-header-inner,
.ivu-drawer-header p {
  font-size: 1.2em !important;
  color: #515a6e !important;
  font-weight: 700 !important;
}
</style>
